<template>
  <div class="monitor-container">
    <!-- 数据表格 -->
    <div v-if="data && data.length > 0" class="data-container">
      <div class="scrollable-table">
        <table class="data-table">
          <thead>
            <tr>
              <th v-for="header in tableHeaders" :key="header" class="table-header">
                {{ header }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in data" :key="item.oI_ORDER_NUM" :class="{ 'highlight-row': index % 2 === 0 }">
              <td>{{ item.oI_ORDER_NUM }}</td>
              <td>{{ item.plaN_MAC }}</td>
              <td>{{ item.slurrY_BATCH }}</td>
              <td>{{ item.formulA_CODE }}</td>
              <td>{{ item.adD_STEP }}</td>
              <td>{{ item.matrial }}</td>
              <td>{{ item.creatE_TIME }}</td>
              <td>{{ item.seT_MACHINE }}</td>
              <td>{{ item.seT_STEP }}</td>
              <td>{{ item.seT_CREATE_TIME }}</td>
              <td :class="getResultColor(item.checK_RESULT)">{{ item.checK_RESULT || '-' }}</td>
              <td>{{ item.alreadY_CYCLE }}</td>
              <td>{{ item.seT_CYCLE }}</td>
              <td>{{ item.uP_CYC_NUM }}</td>
              <td>{{ item.dowN_CYC_NUM }}</td>
              <td>{{ item.cyC_NUM }}</td>
              <td>{{ item.righT_CYCNUM }}</td>
              <td>{{ item.lefT_CYCNUM }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-indicator">
      <div class="loader"></div>
      <span>数据加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-alert">
      <span class="error-icon">!</span> {{ error }}
    </div>

    <!-- 成功提示 -->
    <div v-if="successMessage" class="success-alert fixed-top">
      <span class="success-icon">✓</span> {{ successMessage }}
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
// @ts-ignore
import Speech from 'speak-tts';

import { type DataItems } from '../types'

// 定义 API 响应类型（假设直接返回数据数组）
type ApiResponse = DataItems;

// 状态管理
const data = ref<DataItems>([{
  oI_ORDER_NUM: '初始化',
  plaN_MAC: '初始化',
  slurrY_BATCH: '初始化',
  formulA_CODE: '初始化',
  adD_STEP: '初始化',
  matrial: '初始化',
  creatE_TIME: '初始化',
  diffeR_CREATE_TIME: '初始化',
  seT_MACHINE: '初始化',
  seT_STEP: '初始化',
  seT_CREATE_TIME: '初始化',
  checK_RESULT: '初始化',
  alreadY_CYCLE: '初始化',
  seT_CYCLE: '初始化',
  uP_CYC_NUM: '初始化',
  dowN_CYC_NUM: '初始化',
  cyC_NUM: '初始化',
  righT_CYCNUM: '初始化',
  lefT_CYCNUM: '初始化'
}]);

const loading = ref<boolean>(false);
const error = ref<string | null>(null);
const successMessage = ref<string | null>(null);

// 定时器变量
let refreshTimer: NodeJS.Timeout | null = null;

// 音频状态，常开
const audioEnabled = ref<boolean>(true);

// 配置 axios 实例（建议在单独的 axios.config.ts 中配置）
const apiClient = axios.create({
  baseURL: '/api', // 使用代理前缀
  timeout: 10000,
});

// 请求拦截器（添加全局请求头）
apiClient.interceptors.request.use(
  (config) => {
    loading.value = true;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器（统一处理错误）
apiClient.interceptors.response.use(
  (response) => {
    loading.value = false;
    return response;
  },
  (error) => {
    loading.value = false;
    if (error.response) {
      error.value = `HTTP 错误: ${error.response.status}`;
    } else if (error.request) {
      error.value = '请求未发送';
    } else {
      error.value = '未知错误';
    }
    return Promise.reject(error);
  }
);

// 获取数据
const fetchData = async () => {
  try {
    const res = await apiClient.get<ApiResponse>('/api/Tool/test');
    data.value = res.data || [];
    
    error.value = null;
    // 显示成功提示
    await showSuccessMessage('数据刷新成功');

    // 提取当前不合格项
    const currentFailedItems = data.value
      .filter(item =>
        item.checK_RESULT &&
        (item.checK_RESULT.includes('不合格') ||
          item.checK_RESULT.includes('未达标'))
      )
      .map(item => ({
        orderNum: item.oI_ORDER_NUM,   // 保留订单号
        machine: item.seT_MACHINE      // 新增机器名
      }));

    if (currentFailedItems.length > 0 && audioEnabled.value) {
      try {
        currentFailedItems.forEach(item => {
          const orderNum = item.orderNum
          const machine = item.machine
          playVoice(orderNum, machine);
        });
      } catch (soundError) {
        console.warn('播放音频失败:', soundError);
      }
    }

  } catch (err) {
    console.error('API 请求失败:', err);
  } finally {
    loading.value = false;
  }
};

// 显示成功提示（3秒后自动消失）
const showSuccessMessage = (message: string) => {
  successMessage.value = message;
  // 3秒后清除提示
  setTimeout(() => {
    successMessage.value = null;
  }, 2000);
};


// 播放传参内容 音频播放函数
const playVoice = async (orderNum: string, machine: string) => {
  const speech = new Speech();

  if (speech.hasBrowserSupport()) {
    await speech.init({
      lang: 'zh-CN',
      rate: 1,
      pitch: 1,
    });
    speech.speak({
      text: `订单${orderNum},${machine}机台,粒度检验结果不合格或未达标.`,
      listeners: {
        onstart: () => console.log('开始播放'),
        onend: () => console.log('播放结束'),
      },
    });
  } else {
    alert('当前浏览器不支持语音播报');
  }
};

// 组件挂载时启动定时器
onMounted(() => {
  console.log('组件挂载，启动定时器');
  fetchData(); // 立即加载数据
  // 设置120秒刷新（120000毫秒）
  refreshTimer = setInterval(fetchData, 120000);
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    console.log('组件卸载，清除定时器');
  }
});

// 表格列标题
const tableHeaders = [
  '订单号', '计划机台号', '浆料批号', '配方号', '加料步骤', '物料名称',
  '加料时间', '设参机台号', '设参步骤', '设参时间', '粒度检验结果',
  '已通过循环数', '设定循环数', '上主轴实际转速', '下主轴实际转速',
  '循环泵实际转速', '右搅拌实际循环数', '左搅拌实际循环数'
];

// 根据检验结果设置颜色
const getResultColor = (result: string | null) => {
  if (!result) return 'gray';
  if (result.includes('合格-合格-合格')) return 'green';
  if (result.includes('未达标') || result.includes('不合格')) return 'red';
  return 'yellow';
};
</script>

<style scoped>
/* 全局重置 */
html,
body {
  margin: 0;
  /* 清除默认边距 */
  padding: 0;
  /* 清除默认内边距 */
  width: 100%;
  /* 确保 body 占满屏幕宽度 */
  height: 100%;
  /* 确保高度占满视口 */
  overflow-x: hidden;
  /* 防止水平滚动条 */
}

.monitor-container {
  position: fixed; /* 使用 fixed 定位，确保覆盖整个视口 */
  top: 0;
  left: 0;
  width: 100vw; /* 占满视口宽度 */
  height: 100vh; /* 占满视口高度 */
  padding: 40px;
  box-sizing: border-box;
  background: #1a1a1a;
  color: #e0e0e0;
  font-family: 'Arial', sans-serif;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  display: flex; /* 使用 Flex 布局 */
  justify-content: center; /* 水平居中 */
  align-items: flex-start; /* 顶部对齐 */
  overflow: hidden; /* 防止内容溢出 */
}

.data-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scrollable-table {
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 启用垂直滚动 */
  min-height: 0; /* 避免 flex 子元素最小高度限制 */
  position: relative; /* 新增：为 sticky 定位提供参考系 */
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  position: relative; /* 新增：确保 sticky 定位生效 */
}

/* 鼠标悬停效果 */
.data-table tr:hover {
  background: #00ccff;
  transition: background 0.3s;
}

.data-table td,
.data-table th {
  border-bottom: 1px solid #4a4a4a;
  padding: 12px 15px;
}

.table-header {
  position: sticky !important;;
  top: 0;
  background: #2d2d2d;
  z-index: 10;
  color: #00ccff;
  padding: 15px;
  font-weight: bold;
  text-align: left;
}

.table-header thead tr {
  position: sticky;
  top: 0;
  background: #2d2d2d;
  z-index: 1;
}

.audio-control {
  display: flex;
  justify-content: flex-end;
  /* 主轴靠右 */
  align-items: center;
  /* 交叉轴居中 */
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 10px;
  margin-bottom: 30px;
}

.loader {
  border: 5px solid #f3f3f3;
  border-top: 5px solid #3498db;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
}

.error-alert {
  padding: 20px;
  background: #ff5555;
  color: white;
  border-radius: 10px;
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.success-alert {
  padding: 15px;
  background: #5cb85c;
  color: white;
  border-radius: 10px;
  margin: 20px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  animation: fade-in-out 3s forwards;
}

/* 固定加载/错误提示位置 */
.fixed-top {
  position: fixed;
  top: 20px;
  right: 80%;
  transform: translateX(-50%);
  z-index: 1000;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes fade-in-out {
  0% {
    opacity: 0;
    transform: translateY(-20px);
  }

  20% {
    opacity: 1;
    transform: translateY(0);
  }

  80% {
    opacity: 1;
  }

  100% {
    opacity: 0;
    transform: translateY(20px);
  }
}

.highlight-row {
  background: #3e3e3e;
}

/* 检验结果颜色 */
td:nth-child(11) {
  text-align: center;
  font-weight: bold;
}

.green {
  color: #00ff00;
}

.yellow {
  color: #ffff00;
}

.red {
  color: #ff0000;
}

.gray {
  color: #808080;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .monitor-container {
    padding: 20px;
  }

  .data-table {
    font-size: 0.8rem;
  }
}
</style>